package com.jhws.business.car.service;

import com.alibaba.fastjson.JSON;
import com.jhws.business.car.bo.CarConstant;
import com.jhws.business.car.bo.CarEnteringRecord;
import com.jhws.business.car.bo.CarOrderPayModule;
import com.jhws.business.car.bo.ParkingLot;
import com.jhws.common.Page;
import com.jhws.common.pay.bo.Order;
import com.jhws.common.pay.bo.PayConstants;
import com.jhws.common.pay.service.OrderService;
import com.jhws.core.db.BaseDao;
import com.jhws.core.log.bo.LogConstants;
import com.jhws.core.log.service.ILogService;
import com.jhws.util.*;
import org.apache.commons.collections.MapUtils;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@SuppressWarnings("Duplicates")
@Service
public class CarEnteringRecordServic {
    @Resource
    private BaseDao BaseDao;
    @Resource
    private ILogService ILogService;
    @Resource
    private RedisTemplate stringTemplate;
    @Resource
    private ParkingLotService parkingLotService;
    @Resource
    private OrderService orderService;


    /**
     * 保存停车场出入信息
     *
     * @param carEnteringRecord 停车场出入信息
     */
    public void saveCarEntering(CarEnteringRecord carEnteringRecord) {
        //BaseDao.saveOrUpdate(carEnteringRecord);
        LogHelper.getLogger(LogConstants.loggerCarRecord).debug(GsonUtil.toJson(carEnteringRecord, true));
        if (CarConstant.CAR_BUSSINESS_OUT_TYPE == carEnteringRecord.getBussinessType()) {
            HashOperations hashOperations = stringTemplate.opsForHash();
            String payments = (String) hashOperations.get(CarConstant.REDIS_HEAD_PARKING_LOT + carEnteringRecord.getParkId(), carEnteringRecord.getPlateNumber());
            LogHelper.e("isPay: " + payments);
            if (StringUtils.isEmpty(payments)) {
                ParkingLot parkingLot = parkingLotService.queryParkingLotInfo(carEnteringRecord.getParkId());
                String money = String.valueOf(Double.valueOf(carEnteringRecord.getPayments()));
                /* 生成临时订单基本信息 */
                Order order = new Order();
                order.setId(Long.valueOf(GetId.randomID()));
                order.setAttach(carEnteringRecord.getPlateNumber());
                order.setAttach2(carEnteringRecord.getParkId());
                order.setOrderType(CarOrderPayModule.ORDER_CAR_LANE);
                order.setTime(carEnteringRecord.getTime());
                order.setCommCode(parkingLot.getCommCode());
                order.setOrderState(PayConstants.PAY_STATE_PAID);
                order.setPayableFee(money);
                order.setPayType(PayConstants.PAY_TYPE_CASH);
                order.setPayModule(CarOrderPayModule.PAY_MODULE);
                order.setBody("人工收费");
                Map<String, Object> map = new HashMap<>();
                map.put("plateNumber", carEnteringRecord.getPlateNumber());
                map.put("parkId", carEnteringRecord.getParkId());
                map.put("totalFee", carEnteringRecord.getPayments());
                map.put("actualTotalFee", carEnteringRecord.getPayments());
                order.setDetail(JSON.toJSONString(map));
                order.setTotalFee(money);
                orderService.save(order);
            }
        }
    }

    /**
     * 查询车辆出入记录
     *
     * @param param Map
     * @return 查询车辆出入列表
     */
    @SuppressWarnings("unchecked")
    public Map<String, Object> queryCarEnteringRecordList(Map param) {
        String sql = "SELECT * " + " FROM car_entering_record  WHERE 1=1 ";
        String parkId = MapUtils.getString(param, "parkId", "");
        if (StringUtils.isNotEmpty(parkId)) {
            sql += " and park_id = '" + parkId + "' ";
        }
        String plateNumber = MapUtils.getString(param, "plateNumber", "");
        if (StringUtils.isNotEmpty(plateNumber)) {
            sql += " and plate_number LIKE '%" + plateNumber + "%' ";
        }
        sql += " order by time desc";
        Map<String, Object> result = new HashMap<>();
        List<Map<String, Object>> list;
        Page p = BaseDao.queryPage(sql, Map.class);
        list = p.getList();
        result.put("size", p.getTotalNumber());
        for (Map<String, Object> map : list) {
            int carType = MapUtils.getIntValue(map, "car_type");
            map.put("car_type", CarConstant.carType(carType));
            int cardType = MapUtils.getIntValue(map, "card_type");
            map.put("card_type", CarConstant.cardType(cardType));
            int bussinessType = MapUtils.getIntValue(map, "bussiness_type");
            map.put("bussiness_type", CarConstant.enteringType(bussinessType));
        }
        result.put("list", list);
        result.put("ret_code", 1);
        return result;
    }

    /**
     * 分页查询车辆进出日志
     *
     * @param param
     * @return
     * @throws Exception
     */
    public Map queryCarEnteringRecordLog(Map param) throws Exception {
        String query = "* ";
        String parkId = MapUtils.getString(param, "parkId", "");
        if (StringUtils.isNotEmpty(parkId)) {
            query += " and message.parkId = '" + parkId + "'";
        }
        String plateNumber = MapUtils.getString(param, "plateNumber", "");
        if (StringUtils.isNotEmpty(plateNumber)) {
            query += " and message.plateNumber = '" + plateNumber + "*'";
        }
        Integer timeStart = Math.toIntExact(DateUtil.convert2long(MapUtils.getString(param, "timeStart"), DateUtil.DATE_FORMAT) / 1000);
        Integer timeEnd = Math.toIntExact(DateUtil.convert2long(MapUtils.getString(param, "timeEnd"), DateUtil.DATE_FORMAT) / 1000);
        return ILogService.queryPage(LogConstants.recordsLogStore, LogConstants.topicCarRecord, timeStart, timeEnd, query, CarEnteringRecord.class);
    }

    /**
     * 获取场内车辆
     *
     * @param parkId
     * @return
     */
    public Map queryCarEnteringRecord(String parkId) {
        HashOperations hashOperations = stringTemplate.opsForHash();
        return hashOperations.entries(CarConstant.REDIS_HEAD_PARKING_LOT + parkId);
    }

    /**
     * 获取场内车辆数量
     *
     * @param parkId
     * @return
     */
    public long queryCarEnteringRecordSize(String parkId) {
        HashOperations hashOperations = stringTemplate.opsForHash();
        return hashOperations.size(CarConstant.REDIS_HEAD_PARKING_LOT + parkId);
    }

    /**
     * 删除场内车辆记录
     *
     * @param parkId
     * @param plateNumber
     */
    public void deleteCarEntering(String parkId, String plateNumber) {
        HashOperations hashOperations = stringTemplate.opsForHash();
        hashOperations.delete(CarConstant.REDIS_HEAD_PARKING_LOT + parkId, plateNumber);
    }
}
